import CryptoJS from 'crypto-js';

export function formatTimeDate(dateValue) {
  // 尝试将输入转换为 Date 对象
  const date = new Date(dateValue);

  // 检查是否是有效日期
  if (isNaN(date.getTime())) {
    console.error('Invalid date:', dateValue);
    return null; // 或者返回当前时间或其他默认值
  }

  // 获取年、月、日、时、分、秒
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数，所以加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  // 组装成指定格式
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export function formatSimpleDateTime(dateValue) {
  // 尝试将输入转换为 Date 对象
  const date = new Date(dateValue);

  // 检查是否是有效日期
  if (isNaN(date.getTime())) {
    console.error('Invalid date:', dateValue);
    return null; // 或者返回当前时间或其他默认值
  }

  // 获取年、月、日
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数，所以加1
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}/${month}/${day}`;
}

export function getCategoryList(data, isTopLevelOnly) {
  const categoryMap = new Map(); // 用于存储所有分类的映射
  data.forEach(item => {
    categoryMap.set(item.categoryId, { ...item, children: [...item.children] });
  });

  const result = [];

  data.forEach(item => {
    if (item.parentId === null) { // 只处理顶级分类
      const topLevelCategory = {
        categoryId: item.categoryId,
        name: item.name,
        isVirtual: item.isVirtual,
        children: []
      };

      // 递归查找子分类
      function findChildren(parentId) {
        const children = Array.from(categoryMap.values()).filter(child => child.parentId === parentId);
        if (children.length > 0) {
          children.forEach(child => {
            if (!isTopLevelOnly) { // 只有当不需要仅顶级分类时才添加子分类
              const childCategory = {
                categoryId: child.categoryId,
                name: child.name,
                isVirtual: child.isVirtual,
                children: [] // 初始化子分类数组
              };
              topLevelCategory.children.push(childCategory);

              // 如果需要包含二级分类，则停止递归，否则继续递归查找更深层次的子分类
              if (isTopLevelOnly) {
                return;
              }
              findChildren(child.categoryId);
            }
          });
        }
      }

      findChildren(item.categoryId);
      result.push(topLevelCategory);
    }
  });

  // 如果只需要顶级分类，返回不包含子分类的列表
  if (isTopLevelOnly) {
    return result.map(category => ({
      categoryId: category.categoryId,
      name: category.name,
      isVirtual: category.isVirtual
    }));
  }

  return result;
}

const SECRET_KEY = 'e1f7b1e8-6f7c-4e5d-9d4c-8b8e7a6d5c4b'

export function calculate_signature(data) {
  Object.keys(data).forEach(key => {
    console.log('key: ', key);
    data[key] = String(data[key]);
    console.log('data[key]: ', data[key]);
  })
  console.log('data: ', data);
  return CryptoJS
    .MD5(SECRET_KEY + JSON.stringify(data) + SECRET_KEY)
    .toString(CryptoJS.enc.Hex);
}

// 日期格式化
export function formatDate(time) {
  const timestamp = Date.parse(time);
  // 检查是否解析成功
  if (isNaN(timestamp)) {
    throw new Error("Invalid date string");
  }
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
